package com.zdp.filesync.monitor.service.impl;

import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.alibaba.nacos.shaded.com.google.common.collect.Maps;
import com.zdp.filesync.monitor.config.FileMonitorConfig;
import com.zdp.filesync.monitor.FileMonitorTaskManager;
import com.zdp.filesync.monitor.config.FileMonitorInfo;
import com.zdp.filesync.monitor.service.FileMonitorService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class FileMonitorServiceImpl implements FileMonitorService, InitializingBean {

    @Autowired
    private FileMonitorConfig fileMonitorConfig;

    @Autowired
    private FileMonitorTaskManager fileMonitorTaskManager;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 默认间隔时间5秒
        fileMonitorTaskManager.startMonitor(Optional.ofNullable(fileMonitorConfig).map(FileMonitorConfig::getFileMonitorInfos)
                        .orElseGet(Lists::newArrayList)
                ,Optional.ofNullable(fileMonitorConfig).map(FileMonitorConfig::getInterval).orElseGet(() -> 5000));
    }

    @Override
    public void refreshMonitorTask(FileMonitorConfig newConfig) {
        List<FileMonitorInfo> fileMonitorInfos = newConfig.getFileMonitorInfos();
        Map<String,FileMonitorInfo> newPaths;
        if(!CollectionUtils.isEmpty(fileMonitorInfos)){
            newPaths = fileMonitorInfos.stream()
                    .collect(Collectors.toMap(FileMonitorInfo::getPath, item -> item,(val1,val2)-> val2));
        }else{
            newPaths = Maps.newHashMap();
        }
        // 获取到需要取消的任务
        List<String> delPaths = Lists.newArrayList();
        // 获取到需要修改 commentName的任务
        List<FileMonitorInfo> modifyCommentName  = Lists.newArrayList();
        if(!CollectionUtils.isEmpty(fileMonitorConfig.getFileMonitorInfos())){
            delPaths = fileMonitorConfig.getFileMonitorInfos().stream().map(FileMonitorInfo::getPath)
                    .filter(path -> !newPaths.containsKey(path))
                    .collect(Collectors.toList());

            modifyCommentName = fileMonitorConfig.getFileMonitorInfos().stream().filter(info -> {
                FileMonitorInfo fileMonitorInfo = newPaths.get(info.getPath());
                return Objects.nonNull(fileMonitorInfo) && !StringUtils.equals(info.getCommentName(), fileMonitorInfo.getCommentName());
            }).collect(Collectors.toList());
        }

        fileMonitorTaskManager.cancelMonitorTask(delPaths);
        // 修改已存在任务的 commentName
        modifyCommentName.forEach(info -> fileMonitorTaskManager.modifyCommentName(info.getPath(),info.getCommentName()));
        // 新增任务 （这边不需要筛选，因为在 manager中进行了筛选操作）
        fileMonitorTaskManager.startMonitor(Lists.newArrayList(newPaths.values()),newConfig.getInterval());
        if(Objects.nonNull(newConfig.getInterval())
                && newConfig.getInterval().compareTo(fileMonitorConfig.getInterval()) != 0){
            fileMonitorTaskManager.setInterval(newConfig.getInterval());
        }

    }


}
